<template>
  <div class="app-container home">
    <!-- ========== 快捷入口区域 ========== -->
    <el-row :gutter="20">
      <el-col :sm="24" :lg="24">
        <div class="quick-menu-block"
          style="padding: 15px; background: #f9f9f9; border-radius: 8px; margin-bottom: 20px; border: 1px dashed #ddd;">
          <h4>快捷入口</h4>

          <!-- 已保存的快捷菜单按钮 -->
          <div style="margin-bottom: 10px; min-height: 44px;">
            <el-tag v-for="menu in customMenus" :key="menu.id" size="medium"
              style="margin: 0 8px 8px 0; cursor: pointer; padding: 8px 16px; font-size: 14px;"
              @click="openUrl(menu.url)">
              <!-- @click="openUrl(menu.url)" closable @close="removeMenu(menu.id)"> -->
              {{ menu.menuName }}
            </el-tag>
          </div>

          <!-- 添加按钮 -->
          <el-button type="primary" size="small" icon="el-icon-plus" @click="openAddDialog">
            添加快捷菜单
          </el-button>
        </div>
      </el-col>
    </el-row>

    <!-- ========== 折线图区域 ========== -->
    <el-row :gutter="20">
      <el-col :xs="24" :sm="12" :md="8" :lg="8">
        <blockquote class="text-warning" style="font-size: 14px; padding: 15px;">
          <b>云梦系统访问次数</b>
          <div class="chart-container" style="margin-top: 10px;">
            <div ref="chart2" class="echarts-box"></div>
          </div>
        </blockquote>
      </el-col>
    </el-row>

    <!-- ========== 添加菜单对话框 ========== -->
    <el-dialog title="添加快捷方式" :visible.sync="dialogVisible" width="400px" @close="resetForm">
      <el-form :model="form" :rules="rules" ref="form" label-width="80px">
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="form.menuName" placeholder="例如：Gitee 仓库" />
        </el-form-item>
        <el-form-item label="URL 地址" prop="url">
          <el-input v-model="form.url" placeholder="https://..." />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- ========== 原有内容：公告栏、更新日志、树洞 —— 完全保留 ========== -->
    <el-divider />

    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="12" :lg="8">
        <el-card class="update-log">
          <div slot="header" class="clearfix">
            <span>公告栏</span><br>
            《云梦系统v1.2.0》发布啦！<br>
            QQ交流群：1046324891<br>
            gitee地址：
            <a href="https://gitee.com/Yinhaotian/cd-server.git" target="_blank">
              <el-button type="primary" size="mini" icon="el-icon-link">跳转git</el-button>
            </a>
          </div>
          <div class="body">
          </div>
        </el-card>
      </el-col>

      <!-- 日志展示区域 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="8">
        <el-card class="update-log">
          <div slot="header" class="clearfix">
            <span>更新日志</span>
          </div>

          <!-- 加载状态 -->
          <div v-if="loading" class="loading-text">加载中...</div>

          <!-- 可折叠列表 -->
          <el-collapse v-else-if="updateLogs.length > 0" accordion>
            <el-collapse-item v-for="item in updateLogs" :key="item.noticeId" :title="item.noticeTitle">
              <div class="log-content" v-html="item.noticeContent"></div>
            </el-collapse-item>
          </el-collapse>

          <!-- 无数据提示 -->
          <div v-else class="no-content">暂无更新日志</div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="24" :md="12" :lg="8">
        <el-card class="update-log">
          <div slot="header" class="clearfix">
            <span>信息展示板块</span>
            <div class="body">
              <!-- 添加屏幕尺寸显示 -->
              <div style="margin-top: 10px; font-size: 12px; color: #666;">
                当前屏幕尺寸: {{ screenWidth }}px × {{ screenHeight }}px
              </div>
            </div>
          </div>
          <div class="body">
            <!-- <img src="@/assets/images/transient.png" alt="demo" width="100%" /> -->
            <span style="display: inline-block; height: 30px; line-height: 30px">建设中，敬请期待！</span>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { getMemCountList } from "@/api/system/user";
import { addHomeMenu, getAllHomeMenuByUserId } from "@/api/cd/custom/home-menu";
import { listNotice } from "@/api/system/notice";

export default {
  name: "Index",
  data() {
    return {
      // 报表数据
      lineData: [],
      xdata: [],

      // 屏幕尺寸（确保这个功能正常）
      screenWidth: 0,
      screenHeight: 0,

      // 快捷菜单
      customMenus: [],
      dialogVisible: false,
      form: {
        menuName: '',
        url: ''
      },
      rules: {
        menuName: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }]
      },
      //   url: [
      //     { required: true, message: '请输入URL', trigger: 'blur' },
      //     { pattern: /^https?:\/\/.+/i, message: '请输入有效的 URL（以 http:// 或 https:// 开头）', trigger: 'blur' }
      //   ]
      // },
      chartInstance: null,
      loading: true,
      updateLogs: []
    };
  },
  mounted() {
    this.loadChartData();
    this.loadCustomMenus();
    this.updateScreenSize(); // 初始化屏幕尺寸
    window.addEventListener('resize', this.handleResize); // 监听窗口变化
    this.fetchNotices();
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
  },
  methods: {
    // 加载折线图数据
    loadChartData() {
      getMemCountList().then(response => {
        this.lineData = response.data.ydata;
        this.xdata = response.data.xdata;
        this.$nextTick(() => {
          this.initChart();
        });
      }).catch(err => {
        console.error('获取用户数据失败', err);
      });
    },

    // 初始化 ECharts 图表
    initChart() {
      if (this.chartInstance) {
        this.chartInstance.dispose();
      }
      this.chartInstance = echarts.init(this.$refs.chart2);

      const option = {
        title: {
          text: '用户访问总数趋势',
          left: 'center',
          textStyle: { fontSize: 16, fontWeight: 'bold', color: '#333' }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'line', lineStyle: { color: '#ccc' } },
          formatter: params => `${params[0].name}<br/>注册人数: ${params[0].value}`
        },
        legend: { data: ['总访问人数'], top: '10%', left: 'center' },
        xAxis: {
          type: 'category',
          data: this.xdata,
          name: '时间',
          nameLocation: 'middle',
          nameGap: 30,
          axisLabel: { rotate: 45, fontSize: 12, color: '#666' }
        },
        yAxis: {
          type: 'value',
          name: '访问人数',
          nameLocation: 'middle',
          nameGap: 40,
          splitLine: { show: true, lineStyle: { color: ['#eee'], type: 'dashed' } },
          axisLabel: { fontSize: 12, color: '#666' }
        },
        series: [{
          name: '访问人数',
          data: this.lineData,
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          lineStyle: { width: 2, color: '#4CAF50' },
          itemStyle: { color: '#4CAF50', borderColor: '#fff', borderWidth: 2 },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(76, 175, 80, 0.3)' },
              { offset: 1, color: 'rgba(76, 175, 80, 0)' }
            ])
          }
        }],
        backgroundColor: '#fff',
        grid: { left: '10%', right: '10%', bottom: '15%', containLabel: true }
      };

      this.chartInstance.setOption(option);
    },

    // 响应窗口变化（确保屏幕尺寸更新）
    handleResize() {
      this.updateScreenSize(); // 更新屏幕尺寸
      if (this.chartInstance) {
        this.chartInstance.resize();
      }
    },

    updateScreenSize() {
      this.screenWidth = window.innerWidth;
      this.screenHeight = window.innerHeight;
    },

    // 快捷菜单方法
    loadCustomMenus() {
      getAllHomeMenuByUserId().then(res => {
        if (res.data) {
          this.customMenus = res.data;
        }
      }).catch(err => {
        this.$message.error('加载快捷菜单失败');
      });
    },

    openAddDialog() {
      this.dialogVisible = true;
    },

    submitForm() {
      this.$refs.form.validate(valid => {
        //if (!valid) return;
        let url = this.form.url.trim();
        // if (!/^https?:\/\//i.test(url)) {
        //   url = 'https://' + url;
        //   this.form.url = url;
        // }
        const data = { menuName: this.form.menuName, url, isDeleted: false };
        addHomeMenu(data).then(res => {
          this.$message.success(res.msg || '添加成功');
          this.dialogVisible = false;
          this.loadCustomMenus();
        }).catch(err => {
          this.$message.error('保存失败');
        });
      });
    },

    resetForm() {
      this.$refs.form.resetFields();
    },

    openUrl(url) {
      window.open(url, '_blank');
    },

    removeMenu(id) {
      this.$confirm('确定要删除该快捷方式吗？', '提示', { type: 'warning' }).then(() => {
        this.customMenus = this.customMenus.filter(item => item.id !== id);
        this.$message.success('已删除');
      }).catch(() => { });
    },
    //getNotice
    fetchNotices() {
      this.loading = true;
      try {
        listNotice().then(res => {
          this.updateLogs = res.rows;
          // 找出 noticeType 为 '2' 的公告
          this.updateLogs = res.rows
            .filter(item => item.noticeType === '2')
            .sort((a, b) => new Date(b.createTime) - new Date(a.createTime)); // 按更新时间倒序排列
        }).catch(err => {
          this.loading = false;
          this.$message.error('查询公告失败');
          console.error('获取公告失败:', err);
          this.currentNotice = { noticeTitle: '更新日志', noticeContent: '<p>数据加载失败，请稍后重试。</p>' };
        });
      } catch (error) {
        this.loading = false;
        console.error('获取公告失败:', error);
        this.currentNotice = {
          noticeTitle: '更新日志',
          noticeContent: '<p>网络错误，无法加载更新日志。</p>'
        };
      }
      this.loading = false;
    }
  }
};
</script>

<style scoped lang="scss">
.home {
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", Arial, sans-serif;
  font-size: 14px; // 适当增大基础字体
  color: #676a6c;
  overflow-x: hidden;

  h4 {
    margin: 0 0 12px 0;
    color: #333;
    font-weight: 600;
  }

  .update-log {
    margin-bottom: 20px;
  }

  .chart-container {
    width: 100%;
    min-height: 300px;
    position: relative;
  }

  .echarts-box {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
  }

  blockquote {
    padding: 15px;
    margin: 20px 0;
    border-left: 5px solid #409eff;
    background-color: #f8f9fa;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  }
}

// 优化：快捷菜单的 el-tag 按钮
::v-deep .quick-menu-block {
  .el-tag {
    // 关键：修复文字被挡住
    height: auto !important;
    line-height: 1.8 !important;
    padding: 10px 18px !important;
    font-size: 14px !important;
    font-weight: 500;
    border-radius: 20px !important;
    border: none !important;
    margin: 0 10px 10px 0 !important;
    cursor: pointer !important;
    transition: all 0.3s ease;

    // 背景颜色（可自定义）
    background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%) !important;
    color: white !important;
    box-shadow: 0 4px 10px rgba(37, 117, 252, 0.3);

    // 悬停效果
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 16px rgba(37, 117, 252, 0.4);
    }

    // 关闭按钮样式优化
    .el-tag__close {
      color: rgba(255, 255, 255, 0.8) !important;
      font-weight: bold !important;

      &:hover {
        color: white !important;
        background: rgba(255, 255, 255, 0.2) !important;
        border-radius: 50% !important;
      }
    }
  }
}

// 优化：添加快捷方式按钮
::v-deep .el-button--small {
  &.el-button--primary {
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    border: none;
    padding: 10px 20px;
    border-radius: 24px;
    font-weight: 600;
    box-shadow: 0 4px 12px rgba(79, 172, 254, 0.4);
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 6px 18px rgba(79, 172, 254, 0.5);
    }
  }
}

// 响应式：小屏幕适配
@media (max-width: 768px) {
  .home {
    font-size: 13px;
  }

  ::v-deep .quick-menu-block {
    .el-tag {
      padding: 8px 14px !important;
      font-size: 13px !important;
    }
  }

  .chart-container {
    min-height: 250px;
  }
}
</style>